<?php
/**
 * Created by PhpStorm.
 * User: ybjaa
 * Date: 2017/5/8
 * Time: 11:15
 */

namespace App\Business\Menu;


use App\Business\BusBase;
use App\Business\ReturnResult;
use App\Models\menus_manage;
use Illuminate\Support\Facades\DB;

class CreateMenu extends BusBase
{

    public $menuName;
    public $parentID;
    public $menuURL;
    public $nextID;
    public $isDelete;
    public $isWrite;


    protected function Handle()
    {
        //1检测字段是否为空
        if(!$this->CheckFiledsIsNotNull($this->menuName)) return ReturnResult::Error(null,"名称无效");


        //2.检测在非顶层节点情况下，父节点是否存在，若存在，检测子节点是否存在，存在取出nextID=null的节点
        if($this->parentID!==0)
        {
            $parentMenu=menus_manage::where('ID', $this->parentID)->first();
            if($parentMenu===null) ReturnResult::Error(null,"参数错误");
        }

        //开启事务

        DB::beginTransaction();


        //1.查找当前节点的nextID==null的节点

        $previousCount=menus_manage::where('parentID', $this->parentID)->count();

        $previousMenu=null;

        if($previousCount>0)
        {
            $previousMenu=menus_manage::where('parentID', $this->parentID)->
            where("nextID",null)->first();
            if($previousMenu===null)
            {
                DB::rollBack();
                return ReturnResult::Error(null,"参数错误");
            }
        }

        $menu=new menus_manage();
        $menu->menuName=$this->menuName;
        $menu->menuURL=$this->menuURL;
        $menu->isDelete=$this->isDelete;
        $menu->isWrite=$this->isWrite;
        $menu->parentID=$this->parentID;
        $menu->nextID=null;

        $menu->save();



        $id=$menu->ID;

        if($previousMenu!=null)
        {
            $previousMenu->nextID=$id;
            $previousMenu->save();
        }

        DB::commit();

        return ReturnResult::Success($id);




    }

    public function GetBusinessName()
    {
        return "创建菜单";
    }


}